local DIY = require "packages.diy_utility.diy_utility"

local skel = fk.CreateSkill {
  name = "emo__jiaozhen",
  tags = {DIY.ReadySkill},
}

Fk:loadTranslationTable{
  ["emo__jiaozhen"] = "叫阵",
  [":emo__jiaozhen"] = "蓄势技，出牌阶段开始时，你依次选择是否发动<a href=':emo_tiaoxin'>“挑衅”</a>，<a href=':emo_ex__tiaoxin'>“挑衅（界）”</a>与<a href=':emo_mou__tiaoxin'>“挑衅（谋）”</a>且因此使用的牌对你造成的伤害依次为1、2、3，首张因此使用，打出与弃置牌令蓄势进度+1。",

  ["#emo__jiaozhen-ask"] = "",
  ["#emo__jiaozhen-invoke"] = "叫阵：你可以发动“挑衅”，“界挑衅”与“谋挑衅”中任意项",

  ["emo_tiaoxin"] = "标挑衅",
  [":emo_tiaoxin"] = "令一名攻击范围内含你的其他角色选择一项：1.对你使用一张【杀】；2.你弃置其一张牌。",
  ["emo_ex__tiaoxin"] = "界挑衅",
  [":emo_ex__tiaoxin"] = "令一名其他角色选择一项：1.对你使用一张【杀】（须合法）；2.你弃置其一张牌。", -- 须合法指的是有距离限制
  ["emo_mou__tiaoxin"] = "谋挑衅",
  [":emo_mou__tiaoxin"] = "选择一项令一名其他角色执行：1.将一张手牌当作【决斗】对你使用，否则本回合不能使用或者打出手牌；2.对你使用一张【杀】，否则被你弃置一张牌。背水：本回合你与其受到的伤害均+1。",

  ["#emo_tiaoxin-slash"] = "挑衅：对 %src 使用一张【杀】，否则其弃置你一张牌",
  ["emo_tiaoxin_ask_duel"] = "其对你用决斗，否则其不能用牌",
  ["emo_tiaoxin_ask_slash"] = "其对你使用杀，否则你弃他牌",
  ["emo_tiaoxin_ask_both"] = "背水：本回合你俩受伤害+1",
  ["@@emo_tiaoxin_ban-turn"] = "挑衅:禁牌",
  ["@@emo_tiaoxin_damage-turn"] = "挑衅:受伤+1",
  ["#emo_tiaoxin-duel"] = "挑衅:将1张手牌当作【决斗】对%src使用，否则本回合不能使用打出手牌",
  ["#emo_tiaoxin-choose"] = "对一名角色发动“%arg”",

  ["$emo__jiaozhen1"] = "",
  ["$emo__jiaozhen2"] = "",
}

--- 拆开来好写点 因为lua没有continue
---@param player ServerPlayer @ 发动者
---@param index integer
local function doTiaoxin(player, index)
  local room = player.room
  if player.dead then return end
  local targets = room:getOtherPlayers(player, false)
  local all = {"emo_tiaoxin", "emo_ex__tiaoxin", "emo_mou__tiaoxin"}
  local choice = all[index]
  if choice == "emo_tiaoxin" then
    targets = table.filter(targets, function (p) return p:inMyAttackRange(player) end)
  end
  if #targets == 0 then return end
  local to = room:askToChoosePlayers(player, {
    skill_name = skel.name, min_num = 1, max_num = 1, targets = targets,
    prompt = "#emo_tiaoxin-choose:::" .. choice
  })[1]
  if not to then return end
  --- 普通版挑衅
  local tiaoxin  = function ()
    local use = room:askToUseCard(to, {
      skill_name = skel.name,
      pattern = "slash",
      prompt = "#emo_tiaoxin-slash:"..player.id,
      extra_data = {
        exclusive_targets = {player.id},
        bypass_times = true,
      }
    })
    if use then
      use.extraUse = true
      use.extra_data = use.extra_data or {}
      use.extra_data.emoJiaozhenDamage = { player.id, index}
      room:useCard(use)
    elseif not to:isNude() and not player.dead then
      local cid = room:askToChooseCard(player, {target = to, flag = "he", skill_name = skel.name})
      room:throwCard(cid, skel.name, to, player)
      -- 因弃置增加蓄势进度
      if player:getMark("emo__jiaozhen_throw-phase") == 0 then
        room:setPlayerMark(player, "emo__jiaozhen_throw-phase", 1)
      end
    end
  end

  if choice ~= "emo_mou__tiaoxin" then
    tiaoxin()
  else -- 谋挑衅
    local ch = room:askToChoice(player, {
      skill_name = skel.name, choices = {"emo_tiaoxin_ask_duel", "emo_tiaoxin_ask_slash", "emo_tiaoxin_ask_both"}
    })
    if ch == "emo_tiaoxin_ask_both" then
      room:setPlayerMark(player, "@@emo_tiaoxin_damage-turn", 1)
      room:setPlayerMark(to, "@@emo_tiaoxin_damage-turn", 1)
    end
    if to.dead or player.dead then return end
    if ch ~= "emo_tiaoxin_ask_slash" then
      local cards = table.filter(to:getCardIds("h"), function (id)
        local c = Fk:cloneCard("duel")
        c.skillName = skel.name
        c:addSubcard(id)
        return to:canUseTo(c, player)
      end)
      if #cards > 0 then
        cards = room:askToCards(to, {
          min_num = 1, max_num = 1, skill_name = skel.name, pattern = tostring(Exppattern{ id = cards }),
          prompt = "#emo_tiaoxin-duel:"..player.id,
        })
      end
      if #cards == 0 then
        room:setPlayerMark(to, "@@emo_tiaoxin_ban-turn", 1)
      else
        local card = Fk:cloneCard("duel")
        card.skillName = skel.name
        card:addSubcard(cards[1])
        room:useCard{
          from = to, tos = {player}, card = card,
          extra_data = { emoJiaozhenDamage = { player.id, index } }
        }
      end
    end
    if to.dead or player.dead then return end
    if ch ~= "emo_tiaoxin_ask_duel" then
      tiaoxin()
    end
  end
end

skel:addEffect(fk.EventPhaseStart, {
  anim_type = "control",
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(skel.name) and player.phase == Player.Play
    and table.find(player.room.alive_players, function (p) return p ~= player end)
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askToSkillInvoke(player, {skill_name = skel.name, prompt = "#emo__jiaozhen-invoke"})
  end,
  on_use = function (self, event, target, player, data)
    for i = 1, 3 do
      doTiaoxin(player, i)
    end
    local num = player:getMark("emo__jiaozhen_throw-phase") + player:getMark("emo__jiaozhen_use-phase") +
    player:getMark("emo__jiaozhen_resp-phase")
    if num == 0 then return end
    DIY.changeReadyProgress(player, skel.name, num, skel.name)
  end,
})

-- 因挑衅使用杀/决斗令蓄势进度+1
skel:addEffect(fk.CardUsing, {
  is_delay_effect = true,
  mute = true,
  can_trigger = function (self, event, target, player, data)
    if player:getMark("emo__jiaozhen_use-phase") == 0 and data.extra_data
     and data.extra_data.emoJiaozhenDamage and data.extra_data.emoJiaozhenDamage[1] == player.id then
      return DIY.isReadying(player, skel.name)
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "emo__jiaozhen_use-phase", 1)
  end,
})

-- 响应决斗打出牌令蓄势进度+1
skel:addEffect(fk.CardResponding, {
  is_delay_effect = true,
  mute = true,
  can_trigger = function (self, event, target, player, data)
    if player:getMark("emo__jiaozhen_resp-phase") == 0 and DIY.isReadying(player, skel.name) then
      local e = data.responseToEvent
      return e and e.card and table.contains(e.card.skillNames, skel.name)
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "emo__jiaozhen_resp-phase", 1)
  end,
})

--- 修改对方因挑衅使用使用杀/决斗对我的伤害
skel:addEffect(fk.PreDamage, {
  can_refresh = function (self, event, target, player, data)
    return player == data.to
  end,
  on_refresh = function (self, event, target, player, data)
    local useEvent = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
    if useEvent == nil then return end
    local use = useEvent.data
    if use.card == data.card and use.extra_data and use.extra_data.emoJiaozhenDamage and player.id == use.extra_data.emoJiaozhenDamage[1] then
      data.damage = use.extra_data.emoJiaozhenDamage[2]
    end
  end,
})

-- 背水效果：双方受伤+1
skel:addEffect(fk.DamageInflicted, {
  is_delay_effect = true,
  mute = true,
  can_trigger = function (self, event, target, player, data)
    return target == player and player:getMark("@@emo_tiaoxin_damage-turn") ~= 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    data:changeDamage(1)
  end,
})

skel:addEffect("prohibit", {
  prohibit_use = function(self, player, card)
    if player:getMark("@@emo_tiaoxin_ban-turn") ~= 0 then
      local subcards = Card:getIdList(card)
      return table.find(subcards, function(id) return table.contains(player:getCardIds("h"), id) end)
    end
  end,
  prohibit_response = function (self, player, card)
    if player:getMark("@@emo_tiaoxin_ban-turn") ~= 0 then
      local subcards = Card:getIdList(card)
      return table.find(subcards, function(id) return table.contains(player:getCardIds("h"), id) end)
    end
  end,
})

return skel
